package com.ccjt.efcfs.enums;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 枚举接口
 *
 * @param <E>
 */
public class EnumHelper<E extends IEnum> {

    private final Class<E> enumType;

    public EnumHelper(Class<E> enumType) {
        this.enumType = enumType;
    }

    /**
     * 根据key转换枚举类型
     */
    public static <E extends IEnum> E valueOf(Class<E> enumType, Object key) {
        E[] all = enumType.getEnumConstants();
        if (all == null || all.length == 0) {
            return null;
        }

        for (E e : all) {
            if (Objects.equals(key, e.getKey())) {
                return e;
            }
        }
        return null;
    }

    public static <E extends IEnum> E valueOfDesc(Class<E> enumType, Object desc) {
        E[] all = enumType.getEnumConstants();
        if (all == null || all.length == 0) {
            return null;
        }

        for (E e : all) {
            if (Objects.equals(desc, e.getDesc())) {
                return e;
            }
        }
        return null;
    }

    /**
     * 获取枚举List列表
     */
    public static <E extends IEnum> List<Map<Object, Object>> getEnumList(Class<E> enumType) {
        E[] all = enumType.getEnumConstants();
        if (all == null || all.length == 0) {
            return null;
        }
        List<Map<Object, Object>> list = new ArrayList<>();
        for (E e : all) {
            Map<Object, Object> map = new HashMap<>();
            map.put("key", e.getKey());
            map.put("value", e.getDesc());
            list.add(map);
        }
        return list;
    }

    public E valueOf(Object key) {
        return valueOf(this.enumType, key);
    }
}
